package com.dq.controller.api.merchant.my;

import com.dq.context.event.user.UserEditPhoneEvent;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.EvaluateQuery;
import com.dq.controller.in.RestDayRecordQuery;
import com.dq.controller.api.merchant.in.request.*;
import com.dq.controller.in.request.RestDayRecordRequest;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.evaluation.EvaluationRecord;
import com.dq.domain.evaluation.EvaluationRecordTemplate;
import com.dq.domain.org.Org;
import com.dq.domain.org.OrgHonorWall;
import com.dq.domain.record.RestDayRecord;
import com.dq.domain.sys.user.user.OrgUser;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author liuhui
 * @date 2019/11/22 0022 15:20:50
 */
@RestController
@RequestMapping("/api/merchant/my")
@Api(description = "门店 我的模块管理")
public class MerchantMyController extends AllService {

    @Value("${oss-show-url}")
    private String ossShowUrl;

    @PostMapping("/editPwd")
    @ApiOperation("修改当前用户密码")
    public Vo editPwd(@RequestBody EditPwdRequest editPwdRequest)throws AdminException{
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        if(!PasswordUtil.verify(editPwdRequest.getOldPwd(),orgUser.getPassword())){throw new AdminException("旧密码不正确");}
        orgUser.setPassword(sysUserService.getPassword(editPwdRequest.getNewPwd()));
        OrgUser newUser = orgUserRepository.save(orgUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @PostMapping("/editPhone/sendSms")
    @ApiOperation("修改当前用户手机号发送验证码")
    public Vo editPhoneSendSms(){
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        String smsCode = RandomUtil.getNumber(6);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", orgUser.getUsername());
        map.put("smsCode", smsCode);
        eventPublisher.publishEvent(new UserEditPhoneEvent(map));
        shiroService.setSmsCaptchaCache(smsCode,orgUser.getUsername());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/editPhone")
    @ApiOperation("修改当前用户手机号")
    public Vo editPhone(@RequestBody EditPhoneRequest editPhoneRequest)throws AdminException{
        if(!EditCheckUtil.isMobileNO(editPhoneRequest.getPhone())){throw new AdminException("手机号格式不正确");}
        String cacheSms = shiroService.getSmsCaptchaCache(editPhoneRequest.getPhone());
        if(!cacheSms.equals(editPhoneRequest.getSmdCode())){throw new AdminException("验证码不正确");}
        OrgUser orgUser = (OrgUser) shiroService.getUser();
        orgUser.setUsername(editPhoneRequest.getPhone());
        OrgUser newUser = orgUserRepository.save(orgUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @GetMapping("/editNickName/{nickName}")
    @ApiOperation("修改昵称")
    public Vo editNickName(@PathVariable String nickName)throws AdminException{
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        orgUser.setLocalNickName(nickName);
        orgUser.setUserRealcName(nickName);
        OrgUser newUser = orgUserRepository.save(orgUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @GetMapping("/signOut")
    @ApiOperation("退出登陆")
    public Vo signOut(){
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/userImgEdit")
    @ApiOperation("用户头像修改")
    public Vo userImgEdit(@ApiParam(value = "用户图片") MultipartFile file)throws IOException,AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!EditCheckUtil.isImage(suffix)){throw new AdminException("图片格式不正确");}
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        String fileName = ossService.upload(FileUtil.save(file));
        orgUser.setHeadImg(ossShowUrl+fileName);
        OrgUser newUser = orgUserRepository.save(orgUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    /*****************************门店信息操作****************************************/
    @PostMapping("/orgLogoEdit")
    @ApiOperation("门店logo修改")
    public Vo orgLogoEdit(@ApiParam(value = "门店logo") MultipartFile file)throws IOException,AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!EditCheckUtil.isImage(suffix)){throw new AdminException("图片格式不正确");}
        String fileName = ossService.upload(FileUtil.save(file));
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        Org org =  dao.get(Org.class,orgUser.getSection().getId());
        org.setOrgImg(ossShowUrl+fileName);
        Org newOrg = orgRepository.save(org);
        orgUser.setSection(newOrg);
        OrgUser newUser = dao.get(OrgUser.class,orgUser.getId());
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @GetMapping("/orgNameEdit/{orgName}")
    @ApiOperation("门店名称修改")
    public Vo orgNameEdit(@PathVariable String orgName){
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        Org org =  dao.get(Org.class,orgUser.getSection().getId());
        org.setSimpleName(orgName);
        Org newOrg = orgRepository.save(org);
        orgUser.setSection(newOrg);
        OrgUser newUser = dao.get(OrgUser.class,orgUser.getId());
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @PostMapping("/orgAddressEdit")
    @ApiOperation("门店地址修改")
    public Vo addressEdit(@RequestBody Org orgEdit){
        OrgUser orgUser = (OrgUser)shiroService.getUser();
        Org org =  dao.get(Org.class,orgUser.getSection().getId());
        BeanUtils.copyProperties(orgEdit,org, BeanNullUtil.getNullPropertyNames(orgEdit));
        Org newOrg = orgRepository.save(org);
        orgUser.setSection(newOrg);
        OrgUser newUser = dao.get(OrgUser.class,orgUser.getId());
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @PostMapping("/evaluateList")
    @ApiOperation("评价记录")
    public Vo evaluateList(@RequestBody EvaluateQuery evaluateQuery)throws AdminException{
        if(null==evaluateQuery.getPage() || null==evaluateQuery.getSize()){throw new AdminException("页数和页长参数不存在"); }
        List<EvaluationRecord> evaluationRecordList =  evaluationRecordService.findbyWhere(evaluateQuery);
        Long totalCount = evaluationRecordService.countbyWhere(evaluateQuery);
        List<EvaluationRecord.OrgEvaluationRecordVo> orgEvaluationRecordVos = new ArrayList<>();
        evaluationRecordList.forEach(evaluationRecord -> {
            orgEvaluationRecordVos.add(evaluationRecord.toOrgEvaluationRecordVo());
        });
        PageInfo pageInfo = new PageInfo(orgEvaluationRecordVos);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @GetMapping("/evaluateDetail/{evaluateId}")
    @ApiOperation("评价详情")
    public Vo evaluateDetail(@PathVariable Long evaluateId)throws AdminException{
        EvaluationRecord evaluationRecord = dao.get(EvaluationRecord.class,evaluateId);
        if(null==evaluationRecord){throw new AdminException("评价记录不存在");}
        List<EvaluationRecordTemplate> evaluationRecordTemplateList = evaluationRecordTemplateRepository.findByEvaluationRecord(evaluationRecord);
        return new Vo(evaluationRecord.toOrgEvaluationDetailVo((List<EvaluationRecordTemplate.Vo>)VO.toVOCollection(evaluationRecordTemplateList)));
    }

    @GetMapping("/orgHonorWallList/{page}/{size}")
    @ApiOperation("分页检索门店荣誉墙")
    public Vo orgHonorWallList(@PathVariable Integer page,@PathVariable Integer size){
        Org org = loginTemplate.getOrg();
        Page<OrgHonorWall> orgHonorWallPage = orgHonorWallRepository.findBySysDeptAndDeletedFalse(org,PageableUtil.get(page,size));
        Long totalCount = orgHonorWallRepository.countBySysDeptAndDeletedFalse(org);
        List<OrgHonorWall.OrgHonorWallListVo> orgHonorWallListVos = new ArrayList<>();
        if(null!=orgHonorWallPage){
            orgHonorWallPage.getContent().forEach(orgHonorWall -> {
                orgHonorWallListVos.add(orgHonorWall.toOrgHonorWallListVo());
            });
        }
        PageInfo pageInfo  = new PageInfo(orgHonorWallListVos);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @PostMapping("/userHonorWallImgEdit/{userId}")
    @ApiOperation("用户荣誉墙头像修改/上传")
    public Vo userHonorWallImgEdit(@PathVariable Long userId , @ApiParam(value = "用户荣誉墙头像上传") MultipartFile file)throws IOException,AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!EditCheckUtil.isImage(suffix)){throw new AdminException("图片格式不正确");}
        StaffUser staffUser = dao.get(StaffUser.class,userId);
        if(null==staffUser){throw new AdminException("该用户不存在");}
        String fileName = ossService.upload(FileUtil.save(file));
        staffUser.setHonorWallStaffImage(ossShowUrl+fileName);
        staffUserRepository.save(staffUser);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("用户荣誉墙修改")
    @PostMapping("edit")
    public Vo edit(@RequestBody HonorWallEditRequest request) throws AdminException, IOException {
        SysUser sysUser = shiroService.getUser();
        if(request.getUserId() ==null){
            throw new AdminException("请选择技师");
        }
        StaffUser staffUser = dao.get(StaffUser.class,request.getUserId());
        if(staffUser == null){
            throw new AdminException("请重新选择技师");
        }
        OrgHonorWall o = new OrgHonorWall();
        if(request.getId() != null){
           o=dao.get(OrgHonorWall.class,request.getId());
        }else {
            if(orgHonorWallRepository.findBySysDeptAndStaffUserAndDeletedFalse((Org) sysUser.getSection(),staffUser).size()>0){
                throw new AdminException("此技师已存在荣誉墙");
            }
        }
        o.setStaffUser(staffUser);
        o.setSysDept((Org) sysUser.getSection());
        orgHonorWallRepository.save(o);
        staffUser.setHonorWallStaffImage(request.getUrl());
        staffUser.setHonorWallInfomation(request.getContent());
        staffUserRepository.save(staffUser);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("删除荣誉墙")
    @PostMapping("delete/{id}")
    public Vo delete(@PathVariable Long id)throws AdminException{
        OrgHonorWall orgHonorWall = dao.get(OrgHonorWall.class,id);
        if(orgHonorWall == null){
            throw new AdminException("请重新选择");
        }
        orgHonorWall.setDeleted(true);
        orgHonorWallRepository.save(orgHonorWall);
        return new Vo(HttpStatus.OK);
    }

    @GetMapping("/honorWallUserList/{name}")
    @ApiOperation("用户荣誉墙名称多条件检索")
    public Vo honorWallUserList(@PathVariable String name){
        /*OrgUser orgUser = (OrgUser) shiroService.getUser();
        List<StaffUser> staffUserList = staffUserRepository.findBySectionAndStaffUserStatusAndUserRealcNameLike(orgUser.getSection(), StaffUser.StaffUserStatus.on,"%"+name.trim()+"%");
        List<StaffUser.StaffUserVo> staffUserVoList = new ArrayList<>();
        staffUserList.forEach(staffUser -> {
            staffUserVoList.add(staffUser.toStaffUserVo());
        });
        PageInfo pageInfo  = new PageInfo(staffUserVoList);
        return new Vo(pageInfo);*/
        return null;
    }

    @PostMapping("/honorWallUserAdd")
    @ApiOperation("荣誉员工添加")
    public Vo honorWallUserAdd(@RequestBody HonorWallRequest honorWallRequest)throws AdminException{
        SysUser sysUser = shiroService.getUser();
        if(StringUtils.isEmpty(honorWallRequest.getContent()) || null==honorWallRequest.getUserId()){throw new AdminException("缺少必要的请求参数");}
        StaffUser staffUser = dao.get(StaffUser.class,honorWallRequest.getUserId());
        if(null==staffUser){throw new AdminException("该员工不存在");}
        if(orgHonorWallRepository.findBySysDeptAndStaffUserAndDeletedFalse((Org) sysUser.getSection(),staffUser).size()>0){
            throw new AdminException("此技师已存在荣誉墙");
        }
        OrgHonorWall orgHonorWall = new OrgHonorWall();
        orgHonorWall.setStaffUser(staffUser);
        Org org = loginTemplate.getOrg();
        orgHonorWall.setSysDept(org);
        orgHonorWallRepository.save(orgHonorWall);
        staffUser.setHonorWallStaffImage(honorWallRequest.getUrl());
        staffUser.setHonorWallInfomation(honorWallRequest.getContent());
        staffUserRepository.save(staffUser);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/restDayRecord")
    @ApiOperation("多条件检索休息日记录")
    public Vo restDayRecoedList(@RequestBody RestDayRecordQuery restDayRecordQuery)throws AdminException{
        if(null==restDayRecordQuery.getPage() || null==restDayRecordQuery.getSize()){throw new AdminException("页数和页长参数不存在"); }
        Org org = loginTemplate.getOrg();
        List<RestDayRecord> restDayRecordList = restDayRecordService.findByWhere(restDayRecordQuery,org);
        Long totalCount = restDayRecordService.countByWhere(restDayRecordQuery,org);
        PageInfo pageInfo  = new PageInfo((List<RestDayRecord.Vo>)VO.toVOCollection(restDayRecordList));
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @PostMapping("/restDatRecordAdd")
    @ApiOperation("门店休息日新增")
    public Vo restDatRecordAdd(@RequestBody RestDayRecordRequest restDayRecordRequest)throws AdminException{
        if(StringUtils.isEmpty(restDayRecordRequest.getReason()) || null==restDayRecordRequest.getBeginTime() || null==restDayRecordRequest.getEndTime()){throw new AdminException("缺少必要的请求参数");}
        Org org = loginTemplate.getOrg();
        RestDayRecord restDayRecord = new RestDayRecord(restDayRecordRequest.getBeginTime(),restDayRecordRequest.getEndTime(),restDayRecordRequest.getReason(),org);
        restDayRecordRepository.save(restDayRecord);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/deleteRestDay/{id}")
    @ApiOperation("删除休息日")
    public Vo deleteRestDay(@PathVariable Long id)throws AdminException{
        RestDayRecord dayRecord = dao.get(RestDayRecord.class,id);
        if(dayRecord == null){
            throw new AdminException("请重新选择");
        }
        dayRecord.setDeleted(true);
        restDayRecordRepository.save(dayRecord);
        return new Vo(HttpStatus.OK);
    }

}
